package com.ccys.cms.service.masterData.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ccys.cms.service.masterData.CompanyService;
import com.ccys.common.vo.ResponseResult;
import com.ccys.db.dto.masterData.CompanyIdDto;
import com.ccys.db.dto.masterData.CompanyPageQueryDto;
import com.ccys.db.dto.masterData.CompanySaveDto;
import com.ccys.db.entity.TblCompany;
import com.ccys.db.entity.TblPricingTiming;
import com.ccys.db.mapper.TblCompanyMapper;
import com.ccys.db.mapper.TblPricingTimingMapper;
import com.ccys.db.page.PageDto;
import com.ccys.db.rely.service.impl.BaseServiceImpl;
import com.ccys.db.service.BaseTblAuditTrailWebService;
import com.ccys.db.vo.masterData.CompanyPageQueryVo;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * @program: WhiteCoat
 * @description: 集团接口实现类
 * @author: ZhangJingCan
 * @create: 2023-12-14 10:39
 **/

@Service
public class CompanyServiceImpl extends BaseServiceImpl<TblCompany> implements CompanyService {

    /**
     * 集团
     */
    @Resource
    private TblCompanyMapper tblCompanyMapper;

    /**
     * 问诊价格设置
     */
    @Resource
    private TblPricingTimingMapper tblPricingTimingMapper;

    /**
     * 用于保存修改状态日志
     */
    @Autowired(required = false)
    private BaseTblAuditTrailWebService baseTblAuditTrailWebService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult saveCompany(CompanySaveDto dto) {
        //校验字段值
        if (ObjectUtil.isEmpty(dto.getGroupId()) || ObjectUtil.isEmpty(dto.getCompanyName())
                || ObjectUtil.isEmpty(dto.getCompanyType()) || ObjectUtil.isEmpty(dto.getCompanyAddress())
                || ObjectUtil.isEmpty(dto.getCompanyEmail()) || ObjectUtil.isEmpty(dto.getCompanyPhone())
                || ObjectUtil.isEmpty(dto.getGstRegistered()) || ObjectUtil.isEmpty(dto.getGstRegistrationNo())
                || ObjectUtil.isEmpty(dto.getCompanyLogo())) {
            return ResponseResult.error("Parameter Error!");
        }
        //雪花算法生成code
        long code = IdUtil.getSnowflakeNextId();
        dto.setCompanyCode(code + "");
        //上面校验了字段值 - 新增或修改直接操作即可
        return ResponseResult.update(this.insertOrUpdate(dto));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult deleteCompany(CompanyIdDto dto) {
        //判断
        if (ObjectUtil.isEmpty(dto.getId())) {
            return ResponseResult.error("Parameter Error!");
        }
        //检查当前集团是否存在价格设置数据 - 未删除的
        Example pricingTimingExample = new Example(TblPricingTiming.class);
        pricingTimingExample.createCriteria().andEqualTo("companyId", dto.getId()).andEqualTo("delFlag", 0);
        //查询 - 如果存在则直接返回错误信息
        if (tblPricingTimingMapper.selectCountByExample(pricingTimingExample) > 0) {
            return ResponseResult.error("There is still a consultation price setting under the current company, deletion is prohibited!");
        }
        //以上校验通过 - 准备数据软删除
        TblCompany company = new TblCompany();
        company.setId(dto.getId());
        company.setDelFlag(1);
        //判断是否修改成功 - 返回不同状态
        if (tblCompanyMapper.updateByPrimaryKeySelective(company) > 0) {
            return ResponseResult.success("Delete Successful!");
        }
        return ResponseResult.error("Delete Failed!");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateCompanyStatus(CompanyIdDto dto) {
        //校验
        if (ObjectUtil.isEmpty(dto.getId()) || ObjectUtil.isEmpty(dto.getCompanyStatus())) {
            return ResponseResult.error("Parameter Error!");
        }
        //保存修改状态的日志
        baseTblAuditTrailWebService.saveStatusLog(dto,dto.getCompanyStatus());
        //准备数据修改
        TblCompany company = new TblCompany();
        company.setId(dto.getId());
        company.setCompanyStatus(dto.getCompanyStatus());
        if (tblCompanyMapper.updateByPrimaryKeySelective(company) > 0) {
            return ResponseResult.success("Modified successfully!");
        }
        return ResponseResult.error("Modification failed!");
    }

    @Override
    public ResponseResult<PageInfo<CompanyPageQueryVo>, Object> findPageCompany(CompanyPageQueryDto dto) {
        //检查值范围 - 不在则设置为null
        dto.setCompanyStatus(Optional.ofNullable(dto.getCompanyStatus()).filter(s -> s > -1 && s < 2).orElse(null));
        dto.setPoweredByReferralLetter(Optional.ofNullable(dto.getPoweredByReferralLetter()).filter(s -> s > -1 && s < 2).orElse(null));
        dto.setPoweredByMemo(Optional.ofNullable(dto.getPoweredByMemo()).filter(s -> s > -1 && s < 2).orElse(null));
        dto.setPoweredByReceipt(Optional.ofNullable(dto.getPoweredByReceipt()).filter(s -> s > -1 && s < 2).orElse(null));
        dto.setPoweredByPrescription(Optional.ofNullable(dto.getPoweredByPrescription()).filter(s -> s > -1 && s < 2).orElse(null));
        dto.setPoweredByOtherService(Optional.ofNullable(dto.getPoweredByOtherService()).filter(s -> s > -1 && s < 2).orElse(null));
        //开启分页
        PageDto.startPage();
        PageInfo<CompanyPageQueryVo> info = new PageInfo<>(tblCompanyMapper.findPageCompany(dto));
        return ResponseResult.success(info);
    }
}
